package com.aphrodite.io.sip.dialog;

import com.aphrodite.io.sip.address.NameAddress;
import com.aphrodite.io.sip.header.EventHeader;
import com.aphrodite.io.sip.message.Message;
import com.aphrodite.io.sip.message.SipMethods;
import com.aphrodite.io.sip.provider.MethodIdentifier;
import com.aphrodite.io.sip.provider.SipProvider;
import com.aphrodite.io.sip.provider.SipProviderListener;

/**
 * NotifierDialogAccepter listens for new incoming subscribe requests that
 * create an NotifierDialog.
 */
public class NotifierDialogAccepter implements SipProviderListener {
	/** NotifierDialogAccepterListener that captures new notifier dialogs. */
	NotifierDialogAccepterListener listener;

	/** SipProvider that receives incoming subscribe requests. */
	SipProvider sip_provider;

	/**
	 * Creates a new NotifierDialogAccepter of type <i>method</i>, and starts
	 * listening for incoming subscribe requests.
	 */
	public NotifierDialogAccepter(SipProvider sip_provider, NotifierDialogAccepterListener listener) {
		this.listener = listener;
		sip_provider.addSipProviderListener(new MethodIdentifier(SipMethods.NOTIFY), this);
	}

	/** Stops listening for incoming subscribe requests. */
	public void halt() {
		sip_provider.removeSipProviderListener(new MethodIdentifier(SipMethods.NOTIFY));
	}

	/** Method derived from interface SipListener. */
	public void onReceivedMessage(SipProvider provider, Message msg) {
		NameAddress target = msg.getToHeader().getNameAddress();
		NameAddress subscriber = msg.getFromHeader().getNameAddress();
		EventHeader eh = msg.getEventHeader();
		String event = null;
		String id = null;
		if (eh != null) {
			event = eh.getEvent();
			id = eh.getId();
		}
		if (listener != null)
			listener.onNewNotifierDialog(this, new NotifierDialog(sip_provider, msg, listener), target, subscriber,
					event, id, msg);
	}

}
